import router from './router';
import store from './store';
import NProgress from 'nprogress'; // progress bar
import '@/components/NProgress/nprogress.less'; // progress bar custom style
import infoCache from '@/utils/helper/infoCache';
import { message } from 'ant-design-vue';
import storage from '@/utils/helper/storage';
import { parseURL, isMobile } from '@/utils/util';
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const mobileList = ['/energyManage/analysisReport/beijixingBoard']; // mobile下的
const allowList = ['login', 'register', 'registerResult']; // no redirect allowList
const loginRoutePath = '/user/login';
const checkUrl = () => {
    const { hostname } = document.location;
    const url = `${hostname}:20018`;
    if (url === 'jszt.dwzq.com.cn:20018') {
        // 获取当前URL
        const currentUrl = window.location.href;
        // 创建新的URL字符串，将IP地址替换为指定内容（这里示意为"example.com"）
        const newUrl = currentUrl.replace(/jszt.dwzq.com.cn:20018/g, '10.142.14.27:20018');
        // 通过设置window.location.href属性来进行页面重定向
        window.open(newUrl, '_self');
    }
};
router.beforeEach((to, from, next) => {
    console.log('主应用路由', to);
    if (!window.history.state.current) {
        window.history.state.current = to.path;
    }
    if (!window.history.state.back) {
        window.history.state.back = from.path;
    }
    console.log('主应用路由', window.history.state);
    // 如果是jszt.dwzq.com.cn:20018这个域名，需要进行转化
    if (!isMobile()) {
        checkUrl();
    }
    // 解决多层嵌套路由不缓存问题
    if (to.matched && to.matched.length > 3) {
        for (let i = 0; i < to.matched.length; i++) {
            const element: any = to.matched[i];
            if (element.components.default.name === 'PageView') {
                to.matched.splice(i, 1);
            }
        }
    }

    NProgress.start(); // start progress bar
    const token = to.query.token || to.query.ssoToken;
    const autoLogin = !!token; // 是否自动登陆
    // 如果自动登录，先存储token以便放到请求头中
    if (autoLogin) {
        store.commit('user/SET_TOKEN', token);
    }
    if (localStorage.getItem('token')) {
        if (to.path === loginRoutePath) {
            // 清除缓存内容
            storage.remove('token');
            storage.remove('isWarningChangePwd');
            next();
            NProgress.done();
        } else if (to.path === '/GuidePc') {
            next();
            NProgress.done();
        } else {
            infoCache.init(to.query).then((res) => {
                if (res) {
                    if (!store.getters.addRouters.length) {
                        store.dispatch('permission/GenerateRoutes').then(() => {
                            const redirect = decodeURIComponent((from.query.redirect as string) || to.path);
                            // 移动端除了指定页面都跳转到固定页面
                            if (isMobile() && !mobileList.includes(to.path)) {
                                next({
                                    path: '/GuidePc',
                                    replace: true
                                });
                            } else if (to.path === redirect) {
                                // 去掉地址栏的token参数
                                if (Reflect.has(to.query, 'token')) {
                                    Reflect.deleteProperty(to.query, 'token');
                                }
                                // 去掉地址栏的ssoToken参数
                                if (Reflect.has(to.query, 'ssoToken')) {
                                    Reflect.deleteProperty(to.query, 'ssoToken');
                                }
                                // 使用replace防止浏览器回退误操作
                                next({ ...to, replace: true });
                            } else {
                                // 使用replace，防止回退到登陆页面
                                const { path, query } = parseURL(redirect);
                                next({
                                    path,
                                    query,
                                    replace: true
                                });
                            }
                        });
                    } else {
                        // 移动端除了指定页面都跳转到固定页面
                        if (isMobile() && !mobileList.includes(to.path)) {
                            next({
                                path: '/GuidePc',
                                replace: true
                            });
                        } else {
                            next();
                        }
                    }
                } else {
                    message.error('token无效,获取用户信息失败');
                    next({ path: loginRoutePath });
                }
            });
        }
    } else {
        // 退出登陆之后，会先刷新页面，所以会存redirect，然后清除掉token之后就会去走login页面
        if (allowList.includes(to.name as string)) {
            // 在免登录名单，直接进入
            next();
        } else {
            next({ path: loginRoutePath, query: { redirect: to.fullPath } });
            NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
        }
    }
});

router.afterEach(() => {
    NProgress.done(); // finish progress bar
});
